package cn.dkdoo.blackhorse_transactional.mongo.api.repository;

import cn.dkdoo.blackhorse_transactional.common.TestTraUser;
import cn.dkdoo.blackhorse_transactional.common.TestTraUser2;
import cn.dkdoo.blackhorse_transactional.config.MongodbConfig;
import cn.dkdoo.utils.annotation.DkdTransactional;
import cn.dkdoo.utils.templateDefault.mongo.DefaultMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author nicky
 * @date 2021/5/12 下午2:29
 */
@DkdTransactional
@Component
public class MongodbRepository {
    @Resource(name = MongodbConfig.defaultMongoTemplate)
    DefaultMongoTemplate dkdMongoTemplate;

    public void add(List<TestTraUser> datas) {
        if (CollectionUtils.isEmpty(datas)) {
            datas = new ArrayList<>();
            datas.add(TestTraUser.getOne());
            datas.add(TestTraUser.getOne());
        }
        dkdMongoTemplate.insertAll(datas);
        System.out.println(datas.get(0).getId() + "-Thread.currentThread(): " + Thread.currentThread());
    }


    public void updateMulti(List<TestTraUser> datas) {
        if(CollectionUtils.isEmpty(datas)){
            return;
        }
        Criteria criteria = new Criteria();
        criteria.and("_id").in(datas.stream().map(TestTraUser::getId).collect(Collectors.toList()));
        Update update = new Update();
        update.inc("age", 1);
        update.set("name", "update_" + UUID.randomUUID().toString());
        dkdMongoTemplate.updateMulti(Query.query(criteria), update, TestTraUser.class);
    }

    public void updateMulti2(List<TestTraUser2> datas) {
        if(CollectionUtils.isEmpty(datas)){
            return;
        }
        Criteria criteria = new Criteria();
        criteria.and("_id").in(datas.stream().map(TestTraUser2::getId).collect(Collectors.toList()));
        Update update = new Update();
        update.inc("age", 1);
        update.set("name", "update_" + UUID.randomUUID().toString());
        dkdMongoTemplate.updateMulti(Query.query(criteria), update, TestTraUser2.class);
    }


}
